import Table from "@/components/Table";
import { Space, Button, Popconfirm, message, Modal, Form, InputNumber, Input, FormInstance, Tag } from "antd";
import '@/assets/styles/buttonStyles.css';
import '@/views/system/user/user.css';
import { DataType, ColumnsType } from "@/types/user";
import { useEffect, useState } from "react";
import { getCookie } from "@/utils/cookies";
import { OrderedListOutlined } from "@ant-design/icons";
import React from "react";
import { useNavigate } from "react-router-dom";
import baseUrl from '@/config';
import { Image } from 'antd';
import LoadingIndicator from '@/components/loading';

const User: React.FC = () => {
  const [pageLoading, setPageLoading] = useState(true);
  const [data, setData] = useState<DataType[]>([]);
  const [form] = Form.useForm();
  const [isModalOpenOnesRewards, setIsModalOpenOnesRewards] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isModalOpenAdd, setIsModalOpenAdd] = useState(false);
  const [selInfo, setSelInfo] = useState('');
  const [listNum, setListNum] = useState(0);
  const [editId, setEditId] = useState(0);
  const [editInfo, setEditInfo] = useState(0);

  const showModalEdit = (record: DataType, e?: React.MouseEvent<HTMLElement, MouseEvent>) => {
    if (e) {
      setEditId(record.id);
      setIsModalOpen(true);
    }
  };

  const showModalAdd = () => {
    setIsModalOpenAdd(true);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const handleCancelAdd = () => {
    setIsModalOpenAdd(false);
  };

  const navigateTo = useNavigate();
  useEffect(() => {
    // 判断是否有token，检测用户是否已登录，如果未登录，给出提示，并将其跳转到登录页
    if (getCookie('token') == null) {
      message.error("尚未登录，不得访问！", 1);
      navigateTo("/login");
      return;
    }
    fetchData(); // 调用获取数据的函数
  }, []);


  const fetchData = async () => {
    try {
      const response = await fetch(baseUrl + '/back/wxuser/getUserList', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'token': `${getCookie('token')}`
        },
      });
      setPageLoading(false);
      if (response.ok) {
        // 请求成功
        const data = await response.json();
        // 处理响应数据
        if (data.msg === '操作成功') {
          const dataWithKeys = data.data.map((item: { id: { toString: () => any; }; }) => ({ ...item, key: item.id.toString() }));
          setData(dataWithKeys);
          setListNum(dataWithKeys.length);
        }
        else {
          message.warning(data.msg, 1);
        }
      } else {
        // 请求失败
        console.error('Error:', response.status);
      }
    } catch (error) {
      console.error('Error:', error);
    }
  };

  const handleDelete = async (record: DataType, e?: React.MouseEvent<HTMLElement, MouseEvent>) => {
    if (e) {
      // 处理删除逻辑
      try {
        const response = await fetch(baseUrl + '/back/wxuser/deleteWXUser', {
          method: 'DELETE',
          headers: {
            'Content-Type': 'application/json',
            'token': `${getCookie('token')}`
          },
          body: JSON.stringify(record)
        });

        if (response.ok) {
          // 请求成功
          const data = await response.json();
          // 处理响应数据
          if (data.code === 200) {
            message.success(data.msg, 1);
            fetchData();
          }
          else {
            message.warning(data.msg,);
          }
        } else {
          // 请求失败
          console.error('Error:', response.status);
        }
      } catch (error) {
        console.error('Error:', error);
      }
    }
  };

  // 定义按钮点击事件处理函数
  const handleModifyScore = async () => {
    // 处理修改逻辑
    try {
      const response = await fetch(baseUrl + '/back/wxuser/editScore', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'token': `${getCookie('token')}`
        },
        body: JSON.stringify({
          id: editId,
          score: editInfo,
          nickName: null,
          openid: null,
          avatarUrl: null,
          userType: null,
          wxcode: null,
          rewardsNum: null,
          createTime: null,
          updataTime: null,
          isDeletd: 0
        })
      });

      if (response.ok) {
        // 请求成功
        const data = await response.json();
        // 处理响应数据
        if (data.code === 200) {
          message.success(data.msg, 1);
          fetchData();
        }
        else {
          message.warning(data.msg, 1);
        }
      } else {
        // 请求失败
        console.error('Error:', response.status);
      }
    } catch (error) {
      console.error('Error:', error);
    }
    setIsModalOpen(false);
  };

  const handleAddInfo = () => {
    // 处理新增信息逻辑
    setIsModalOpenAdd(false);
  };

  const columns: ColumnsType<DataType> = [
    {
      title: "序号",
      dataIndex: "index",
      key: "index",
      render: (_, _record, index) => <span>{index + 1}</span>,
    },
    {
      title: "微信名",
      dataIndex: "nickName",
      key: "nickName",
    },
    {
      title: "头像",
      dataIndex: "avatarUrl",
      key: "avatarUrl",
      render: (text) => <Image width={35} src={text} />,
    },
    {
      title: "积分数",
      dataIndex: "score",
      key: "score",
    },
    {
      title: "奖券数",
      dataIndex: "rewardsNum",
      key: "rewardsNum",
    },
    {
      title: "加入时间",
      key: "createTime",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button type="default" onClick={(e) => showModalEdit(record, e)} className="edit-button">
            修改积分
          </Button>
          <Popconfirm
            title="提示"
            description="确定要删除该用户吗？"
            okText="Yes"
            cancelText="No"
            onConfirm={(e) => handleDelete(record, e)}
          >
            <Button danger>删除</Button>
          </Popconfirm>
          <Button type="link" onClick={(e) => getOnesRewards(record, e)} className="info-button">查看奖券信息</Button>
          <Button type="link" onClick={(e) => getOnesRequest(record, e)} className="info2-button">查看请求信息</Button>
          <Button type="link" onClick={(e) => getOnesDispatch(record, e)} className="info3-button">查看调度信息</Button>
        </Space>
      ),
    },
    {
      title: "id",
      dataIndex: "id",
      key: "id",
      className: 'hiddenColumn'
    }
  ];

  const selInfoDetail = async () => {
    try {
      setPageLoading(true);
      const response = await fetch(baseUrl + '/back/wxuser/getUserLikeName?nickName=' + selInfo, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'token': `${getCookie('token')}`
        }
      });
      setPageLoading(false);
      if (response.ok) {
        // 请求成功
        const data = await response.json();
        // 处理响应数据
        if (data.code === 200) {
          const dataWithKeys = data.data.map((item: { id: { toString: () => any; }; }) => ({ ...item, key: item.id.toString() }));
          setData(dataWithKeys);
          setListNum(dataWithKeys.length);
          message.success(data.msg, 1);
        }
        else {
          message.warning(data.msg, 1);
        }
      } else {
        // 请求失败
        console.error('Error:', response.status);
      }
    } catch (error) {
      console.error('Error:', error);
    }
  };

  const SubmitButton = ({ form }: { form: FormInstance }) => {
    const [submittable, setSubmittable] = React.useState(false);

    // Watch all values
    const values = Form.useWatch([], form);

    React.useEffect(() => {
      form.validateFields({ validateOnly: true }).then(
        () => {
          setSubmittable(true);
        },
        () => {
          setSubmittable(false);
        },
      );
    }, [values]);

    return (
      <Button type="primary" htmlType="submit" disabled={!submittable} onClick={selInfoDetail}>
        查询
      </Button>
    );
  };

  const handleSelInfoChange = (event: { target: { value: React.SetStateAction<string>; }; }) => {
    setSelInfo(event.target.value);
  };

  const handleEditInfoChange = (value: number | null) => {
    setEditInfo(value ?? 0);
  };

  interface DataType2 {
    key: string;
    rewardsInfo: string;
    rewardsLimit: string;
    rewardsState: string;
    rewardsImgUrl: string;
    rewardsDate: Date;
    id: number;
  }

  const columns2: ColumnsType<DataType2> = [
    {
      title: "序号",
      dataIndex: "index",
      key: "index",
      render: (_, _record, index) => <span>{index + 1}</span>,
    },
    {
      title: "奖券信息",
      dataIndex: "rewardsInfo",
      key: "rewardsInfo",
    },
    {
      title: "奖券限制",
      dataIndex: "rewardsLimit",
      key: "rewardsLimit",
    },
    {
      title: "奖券状态",
      dataIndex: "rewardsState",
      key: "rewardsState",
      render: (text) => {
        // 根据 text 的值分配不同的 Tag 样式
        if (text === '已领取') {
          return <Tag color="blue">已领取</Tag>;
        } else {
          // 如果 text 不匹配上述条件，则返回默认样式的 Tag
          return <Tag>未领取</Tag>;
        }
      }
    },
    {
      title: "获得时间",
      dataIndex: "rewardsDate",
      key: "rewardsDate",
    },
    {
      title: "id",
      dataIndex: "id",
      key: "id",
      className: 'hiddenColumn'
    },
    {
      title: "rewardsImgUrl",
      dataIndex: "rewardsImgUrl",
      key: "rewardsImgUrl",
      className: 'hiddenColumn'
    }
  ];

  const [data2, setData2] = useState<DataType2[]>([]);

  const handleOnesRewards = () => {
    setIsModalOpenOnesRewards(false);
  };

  const getOnesRewards = async (record: DataType, e?: React.MouseEvent<HTMLElement, MouseEvent>) => {
    if (e) {
      setIsModalOpenOnesRewards(true);
      try {
        const response = await fetch(baseUrl + '/rewardsDetail/getRewardsByNickName?nickName=' + record.nickName, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'token': `${getCookie('token')}`
          },
        });

        if (response.ok) {
          // 请求成功
          const data = await response.json();
          // 处理响应数据
          if (data.msg === '操作成功') {
            const dataWithKeys = data.data.map((item: { id: { toString: () => any; }; }) => ({ ...item, key: item.id.toString() }));
            setData2(dataWithKeys);
          }
          else {
            setData2([]);
            message.warning(data.msg, 1);
          }
        } else {
          // 请求失败
          console.error('Error:', response.status);
        }
      } catch (error) {
        console.error('Error:', error);
      }
    }
  };


  interface DataType3 {
    key: string;
    name: string;
    info: string;
    state: string;
    time: Date;
  }

  const columns3: ColumnsType<DataType3> = [
    {
      title: "序号",
      dataIndex: "index",
      key: "index",
      render: (_, _record, index) => <span>{index + 1}</span>,
    },
    {
      title: "请求区域",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "请求详情",
      dataIndex: "state",
      key: "state",
    },
    {
      title: "请求状态信息",
      dataIndex: "info",
      key: "info",
    },
    {
      title: "最后处理时间",
      dataIndex: "time",
      key: "time",
    },
  ];

  const [isModalOpenOnesRequest, setIsModalOpenOnesRequest] = useState(false);

  const [data3, setData3] = useState<DataType3[]>([]);


  const handleOnesRequest = () => {
    setIsModalOpenOnesRequest(false);
  };

  const getOnesRequest = async (record: DataType, e?: React.MouseEvent<HTMLElement, MouseEvent>) => {
    if (e) {
      setIsModalOpenOnesRequest(true);
      try {
        const response = await fetch(baseUrl + '/bikeRequest/getRequestsByNickName?nickName=' + record.nickName, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'token': `${getCookie('token')}`
          },
        });

        if (response.ok) {
          // 请求成功
          const data = await response.json();
          // 处理响应数据
          if (data.msg === '操作成功') {
            // 将数据转换为数组
            const dataArray = [];
            for (let i = 0; i < data.data.length; i++) {
              if (data.data[i]) {
                dataArray.push(data.data[i]);
              }
            }
            // 使用map()函数对dataArray中的每个元素进行处理，添加key属性
            const dataWithKeys = dataArray.map((item) => ({ ...item, key: item.time }));
            setData3(dataWithKeys);
          }
          else {
            setData3([]);
            message.warning(data.msg, 1);
          }
        } else {
          // 请求失败
          console.error('Error:', response.status);
        }
      } catch (error) {
        console.error('Error:', error);
      }
    }
  };

  const [isModalOpenOnesDispatch, setIsModalOpenOnesDispatch] = useState(false);

  const [data4, setData4] = useState<DataType3[]>([]);


  const handleOnesDispatch = () => {
    setIsModalOpenOnesDispatch(false);
  };

  const getOnesDispatch = async (record: DataType, e?: React.MouseEvent<HTMLElement, MouseEvent>) => {
    if (e) {
      setIsModalOpenOnesDispatch(true);
      try {
        const response = await fetch(baseUrl + '/bikeDispatch/getDispatchListByNickName?nickName=' + record.nickName, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'token': `${getCookie('token')}`
          },
        });

        if (response.ok) {
          // 请求成功
          const data = await response.json();
          // 处理响应数据
          if (data.msg === '操作成功') {
            // 将数据转换为数组
            const dataArray = [];
            for (let i = 0; i < data.data.length; i++) {
              if (data.data[i]) {
                dataArray.push(data.data[i]);
              }
            }
            // 使用map()函数对dataArray中的每个元素进行处理，添加key属性
            const dataWithKeys = dataArray.map((item) => ({ ...item, key: item.time }));
            setData4(dataWithKeys);
          }
          else {
            setData4([]);
            message.warning(data.msg, 1);
          }
        } else {
          // 请求失败
          console.error('Error:', response.status);
        }
      } catch (error) {
        console.error('Error:', error);
      }
    }
  };

  return (
    <>
      <LoadingIndicator loading={pageLoading} />
      <Form form={form} name="validateOnly" layout="inline" autoComplete="off">
        <Form.Item>
          <Button type="primary" className="add-button" onClick={showModalAdd}>
            新增
          </Button>
        </Form.Item>
        <Modal title="新增微信小程序用户" open={isModalOpenAdd} okText="知道了"
          cancelText="取消" onOk={handleAddInfo} onCancel={handleCancelAdd}>
          <p>出于对微信用户隐私和数据保护,非微信平台暂不支持新增微信用户信息,如有需要,请前往微信app进行账号注册!</p>
        </Modal>
        <Form.Item name="name" label="" rules={[{ required: true, message: "查找字段内容不得为空,如不想查找请点击重置!" }]}>
          <Input placeholder="(按微信名模糊查询）" value={selInfo} onChange={handleSelInfoChange} />
        </Form.Item>
        <Form.Item>
          <Space>
            <SubmitButton form={form} />
            <Button htmlType="reset">重置</Button>
          </Space>
        </Form.Item>
        <Tag bordered={true} color="green" className="total-tag">
          共{listNum}条记录
        </Tag>
        <Button type="link" onClick={fetchData}>查询所有</Button>
      </Form>
      <Modal title="请输入要修改的积分数" open={isModalOpen} okText="Yes"
        cancelText="No" onOk={handleModifyScore} onCancel={handleCancel}>
        <Form>
          <Form.Item
            name="score"
            rules={[{ required: true, message: "请填写正确积分数！", type: 'number' }]}
          >
            <InputNumber prefix={<OrderedListOutlined />} size="large" style={{ width: '200px' }} value={editInfo} onChange={handleEditInfoChange} placeholder="默认为0" />
          </Form.Item>
        </Form>
      </Modal>
      <Modal title="奖券详情信息" open={isModalOpenOnesRewards} onOk={handleOnesRewards} onCancel={handleOnesRewards} width="50%"
        bodyStyle={{ maxHeight: '60vh', overflowY: 'auto' }} // 设置最大高度和溢出时显示滚动条
        okText="确定" cancelText="取消">
        <Table columns={columns2} dataSource={data2} />
      </Modal>
      <Modal title="请求详情信息,此处为基本信息,如要查看完整信息请移步[请求管理]" open={isModalOpenOnesRequest} onOk={handleOnesRequest} onCancel={handleOnesRequest} width="50%"
        bodyStyle={{ maxHeight: '60vh', overflowY: 'auto' }} // 设置最大高度和溢出时显示滚动条
        okText="确定" cancelText="取消">
        <Table columns={columns3} dataSource={data3} />
      </Modal>
      <Modal title="请求详情信息,此处为基本信息,如要查看完整信息请移步[调度管理]" open={isModalOpenOnesDispatch} onOk={handleOnesDispatch} onCancel={handleOnesDispatch} width="50%"
        bodyStyle={{ maxHeight: '60vh', overflowY: 'auto' }} // 设置最大高度和溢出时显示滚动条
        okText="确定" cancelText="取消">
        <Table columns={columns3} dataSource={data4} />
      </Modal>
      <Table<DataType> columns={columns} dataSource={data} />
    </>
  );
};

export default User;